package com.heima.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.IUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, ApUser> implements IUserService {
    private final UserMapper userMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
        //判断用户名密码对不对

        if (StringUtils.isEmpty(dto.getPhone())||StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUser dbUser = userMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));

        if (null == dbUser){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //盐
        //12356 +abcd - 加密
        String salt = dbUser.getSalt();
        String inputPassword = dto.getPassword();
        byte[] pass = (salt + inputPassword).getBytes();
        String pw = DigestUtils.md5DigestAsHex(pass);
        if (!pw.equals(dbUser.getPassword())){
           return ResponseResult.errorResult(AppHttpCodeEnum.PHONE_OR_PASSWORD_ERROR);
        }

        //验证成功，返回
        JSONObject result = new JSONObject();
        dbUser.setSalt(null);
        dbUser.setPassword("");
        result.put("user",dbUser);
        result.put("token", AppJwtUtil.getToken(dbUser.getId().longValue()));
        return ResponseResult.okResult(result);
    }
}
